home *** CD-ROM | disk | FTP | other *** search
/ PC World 2008 April / PCWorld_2008-04_cd.bin / v cisle / ozo / zotero-1.0.3.xpi / components / zotero-protocol-handler.js < prev    next >
Text File  |  2008-01-03  |  22KB  |  792 lines

  1. /*
  2.     ***** BEGIN LICENSE BLOCK *****
  3.     
  4.     Copyright (c) 2006  Center for History and New Media
  5.                         George Mason University, Fairfax, Virginia, USA
  6.                         http://chnm.gmu.edu
  7.     
  8.     Licensed under the Educational Community License, Version 1.0 (the "License");
  9.     you may not use this file except in compliance with the License.
  10.     You may obtain a copy of the License at
  11.     
  12.     http://www.opensource.org/licenses/ecl1.php
  13.     
  14.     Unless required by applicable law or agreed to in writing, software
  15.     distributed under the License is distributed on an "AS IS" BASIS,
  16.     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17.     See the License for the specific language governing permissions and
  18.     limitations under the License.
  19.     
  20.     
  21.     Based on nsChromeExtensionHandler example code by Ed Anuff at
  22.     http://kb.mozillazine.org/Dev_:_Extending_the_Chrome_Protocol
  23.     
  24.     
  25.     ***** END LICENSE BLOCK *****
  26. */
  27.  
  28.  
  29. const ZOTERO_SCHEME = "zotero";
  30. const ZOTERO_PROTOCOL_CID = Components.ID("{9BC3D762-9038-486A-9D70-C997AF848A7C}");
  31. const ZOTERO_PROTOCOL_CONTRACTID = "@mozilla.org/network/protocol;1?name=" + ZOTERO_SCHEME;
  32. const ZOTERO_PROTOCOL_NAME = "Zotero Chrome Extension Protocol";
  33.  
  34. // Dummy chrome URL used to obtain a valid chrome channel
  35. // This one was chosen at random and should be able to be substituted
  36. // for any other well known chrome URL in the browser installation
  37. const DUMMY_CHROME_URL = "chrome://mozapps/content/xpinstall/xpinstallConfirm.xul";
  38.  
  39.  
  40. function ChromeExtensionHandler() {
  41.     this.wrappedJSObject = this;
  42.     this._systemPrincipal = null;
  43.     this._extensions = {};
  44.     
  45.     
  46.     /*
  47.      * Report generation extension for Zotero protocol
  48.      *
  49.      * Example URLs:
  50.      *
  51.      * zotero://report/    -- library
  52.      * zotero://report/collection/12345
  53.      * zotero://report/search/12345
  54.      * zotero://report/items/12345-23456-34567
  55.      * zotero://report/item/12345
  56.      *
  57.      * Optional format can be specified after ids
  58.      *
  59.      *  - 'html', 'rtf', 'csv'
  60.      *  - defaults to 'html' if not specified
  61.      *
  62.      * e.g. zotero://report/collection/12345/rtf
  63.      * 
  64.      *
  65.      * Sorting:
  66.      *
  67.      *     - 'sort' query string variable
  68.      *  - format is field[/order] [, field[/order], ...]
  69.      *  - order can be 'asc', 'a', 'desc' or 'd'; defaults to ascending order
  70.      *
  71.      *  zotero://report/collection/13245?sort=itemType/d,title
  72.      */
  73.     var ReportExtension = new function(){
  74.         this.newChannel = newChannel;
  75.         
  76.         function newChannel(uri){
  77.             var ioService = Components.classes["@mozilla.org/network/io-service;1"]
  78.                 .getService(Components.interfaces.nsIIOService);
  79.             
  80.             var Zotero = Components.classes["@zotero.org/Zotero;1"]
  81.                 .getService(Components.interfaces.nsISupports)
  82.                 .wrappedJSObject;
  83.             
  84.             generateContent:try {
  85.                 var mimeType, content = '';
  86.                 
  87.                 var [path, queryString] = uri.path.substr(1).split('?');
  88.                 var [type, ids, format] = path.split('/');
  89.                 
  90.                 // Get query string variables
  91.                 if (queryString) {
  92.                     var queryVars = queryString.split('&');
  93.                     for (var i in queryVars) {
  94.                         var [key, val] = queryVars[i].split('=');
  95.                         switch (key) {
  96.                             case 'sort':
  97.                                 var sortBy = val;
  98.                                 break;
  99.                         }
  100.                     }
  101.                 }
  102.                 
  103.                 switch (type){
  104.                     case 'collection':
  105.                         var col = Zotero.Collections.get(ids);
  106.                         var results = col.getChildItems();
  107.                         break;
  108.                     
  109.                     case 'search':
  110.                         var s = new Zotero.Search(ids);
  111.                         var ids = s.search();
  112.                         break;
  113.                     
  114.                     case 'items':
  115.                     case 'item':
  116.                         var ids = ids.split('-');
  117.                         break;
  118.                         
  119.                     default:
  120.                         var type = 'library';
  121.                         var s = new Zotero.Search();
  122.                         s.addCondition('noChildren', 'true');
  123.                         var ids = s.search();
  124.                 }
  125.                 
  126.                 if (!results) {
  127.                     var results = Zotero.Items.get(ids);
  128.                     
  129.                     if (!results) {
  130.                         mimeType = 'text/html';
  131.                         content = 'Invalid ID';
  132.                         break generateContent;
  133.                     }
  134.                 }
  135.                 
  136.                 var items = [];
  137.                 var itemsHash = {}; // key = itemID, val = position in |items|
  138.                 var searchItemIDs = {}; // hash of all selected items
  139.                 var searchParentIDs = {}; // hash of parents of selected child items
  140.                 var searchChildIDs = {}; // hash of selected chlid items
  141.                 
  142.                 var includeAllChildItems = Zotero.Prefs.get('report.includeAllChildItems');
  143.                 var combineChildItems = Zotero.Prefs.get('report.combineChildItems');
  144.                 
  145.                 for (var i=0; i<results.length; i++) {
  146.                     // Don't add child items directly
  147.                     // (instead mark their parents for inclusion below)
  148.                     var sourceItemID = results[i].getSource();
  149.                     if (sourceItemID) {
  150.                         searchParentIDs[sourceItemID] = true;
  151.                         searchChildIDs[results[i].getID()] = true;
  152.                         
  153.                         // Don't include all child items if any child
  154.                         // items were selected
  155.                         includeAllChildItems = false;
  156.                     }
  157.                     // If combining children or standalone note/attachment, add matching parents
  158.                     else if (combineChildItems || !results[i].isRegularItem()) {
  159.                         itemsHash[results[i].getID()] = items.length;
  160.                         items.push(results[i].toArray(2));
  161.                         // Flag item as a search match
  162.                         items[items.length - 1].reportSearchMatch = true;
  163.                     }
  164.                     searchItemIDs[results[i].getID()] = true;
  165.                 }
  166.                 
  167.                 // If including all child items, add children of all matched
  168.                 // parents to the child array
  169.                 if (includeAllChildItems) {
  170.                     for (var id in searchItemIDs) {
  171.                         if (!searchChildIDs[id]) {
  172.                             var children = [];
  173.                             var item = Zotero.Items.get(id);
  174.                             if (!item.isRegularItem()) {
  175.                                 continue;
  176.                             }
  177.                             var func = function (ids) {
  178.                                 if (ids) {
  179.                                     for (var i=0; i<ids.length; i++) {
  180.                                         searchChildIDs[ids[i]] = true;
  181.                                     }
  182.                                 }
  183.                             };
  184.                             func(item.getNotes());
  185.                             func(item.getAttachments());
  186.                         }
  187.                     }
  188.                 }
  189.                 
  190.                 if (combineChildItems) {
  191.                     // Add parents of matches if parents aren't matches themselves
  192.                     for (var id in searchParentIDs) {
  193.                         if (!searchItemIDs[id]) {
  194.                             var item = Zotero.Items.get(id);
  195.                             itemsHash[id] = items.length;
  196.                             items.push(item.toArray(2));
  197.                         }
  198.                     }
  199.                     
  200.                     // Add children to reportChildren property of parents
  201.                     for (var id in searchChildIDs) {
  202.                         var item = Zotero.Items.get(id);
  203.                         var parentItemID = item.getSource();
  204.                         if (!items[itemsHash[parentItemID]].reportChildren) {
  205.                             items[itemsHash[parentItemID]].reportChildren = {
  206.                                 notes: [],
  207.                                 attachments: []
  208.                             };
  209.                         }
  210.                         if (item.isNote()) {
  211.                             items[itemsHash[parentItemID]].reportChildren.notes.push(item.toArray());
  212.                         }
  213.                         if (item.isAttachment()) {
  214.                             items[itemsHash[parentItemID]].reportChildren.attachments.push(item.toArray());
  215.                         }
  216.                     }
  217.                 }
  218.                 // If not combining children, add a parent/child pair
  219.                 // for each matching child
  220.                 else {
  221.                     for (var id in searchChildIDs) {
  222.                         var item = Zotero.Items.get(id);
  223.                         var parentID = item.getSource();
  224.                         var parentItem = Zotero.Items.get(parentID);
  225.                         
  226.                         if (!itemsHash[parentID]) {
  227.                             // If parent is a search match and not yet added,
  228.                             // add on its own
  229.                             if (searchItemIDs[parentID]) {
  230.                                 itemsHash[parentID] = [items.length];
  231.                                 items.push(parentItem.toArray(2));
  232.                                 items[items.length - 1].reportSearchMatch = true;
  233.                             }
  234.                             else {
  235.                                 itemsHash[parentID] = [];
  236.                             }
  237.                         }
  238.                         
  239.                         // Now add parent and child
  240.                         itemsHash[parentID].push(items.length);
  241.                         items.push(parentItem.toArray(2));
  242.                         if (item.isNote()) {
  243.                             items[items.length - 1].reportChildren = {
  244.                                 notes: [item.toArray()],
  245.                                 attachments: []
  246.                             };
  247.                         }
  248.                         else if (item.isAttachment()) {
  249.                             items[items.length - 1].reportChildren = {
  250.                                 notes: [],
  251.                                 attachments: [item.toArray()]
  252.                             };
  253.                         }
  254.                     }
  255.                 }
  256.                 
  257.                 
  258.                 // Sort items
  259.                 if (!sortBy) {
  260.                     sortBy = 'title';
  261.                 }
  262.                 
  263.                 var sorts = sortBy.split(',');
  264.                 for (var i=0; i<sorts.length; i++) {
  265.                     var [field, order] = sorts[i].split('/');
  266.                     // Year field is really date field
  267.                     if (field == 'year') {
  268.                         field = 'date';
  269.                     }
  270.                     switch (order) {
  271.                         case 'd':
  272.                         case 'desc':
  273.                             order = -1;
  274.                             break;
  275.                         
  276.                         default:
  277.                             order = 1;
  278.                     }
  279.                     
  280.                     sorts[i] = {
  281.                         field: field,
  282.                         order: order
  283.                     };
  284.                 }
  285.                 
  286.                 
  287.                 var collation = Zotero.getLocaleCollation();
  288.                 var compareFunction = function(a, b) {
  289.                     var index = 0;
  290.                     
  291.                     // Multidimensional sort
  292.                     do {
  293.                         // Note and attachment sorting when combineChildItems is false
  294.                         if (!combineChildItems && sorts[index].field == 'note') {
  295.                             if (a.itemType == 'note' || a.itemType == 'attachment') {
  296.                                 var valA = a.note;
  297.                             }
  298.                             else if (a.reportChildren) {
  299.                                 var valA = a.reportChildren.notes[0].note;
  300.                             }
  301.                             else {
  302.                                 var valA = '';
  303.                             }
  304.                             
  305.                             if (b.itemType == 'note' || b.itemType == 'attachment') {
  306.                                 var valB = b.note;
  307.                             }
  308.                             else if (b.reportChildren) {
  309.                                 var valB = b.reportChildren.notes[0].note;
  310.                             }
  311.                             else {
  312.                                 var valB = '';
  313.                             }
  314.                             
  315.                             // Put items without notes last
  316.                             if (valA == '' && valB != '') {
  317.                                 var cmp = 1;
  318.                             }
  319.                             else if (valA != '' && valB == '') {
  320.                                 var cmp = -1;
  321.                             }
  322.                             else {
  323.                                 var cmp = collation.compareString(0, valA, valB);
  324.                             }
  325.                         }
  326.                         else {
  327.                             var cmp = collation.compareString(0,
  328.                                 a[sorts[index].field],
  329.                                 b[sorts[index].field]
  330.                             );
  331.                         }
  332.                         
  333.                         if (cmp == 0) {
  334.                             continue;
  335.                         }
  336.                         
  337.                         var result = cmp * sorts[index].order;
  338.                         index++;
  339.                     }
  340.                     while (result == 0 && sorts[index]);
  341.                     
  342.                     return result;
  343.                 };
  344.                 
  345.                 items.sort(compareFunction);
  346.                 for (var i in items) {
  347.                     if (items[i].reportChildren) {
  348.                         items[i].reportChildren.notes.sort(compareFunction);
  349.                         items[i].reportChildren.attachments.sort(compareFunction);
  350.                     }
  351.                 }
  352.                 
  353.                 // Pass off to the appropriate handler
  354.                 switch (format){
  355.                     case 'rtf':
  356.                         mimeType = 'text/rtf';
  357.                         break;
  358.                         
  359.                     case 'csv':
  360.                         mimeType = 'text/plain';
  361.                         break;
  362.                     
  363.                     default:
  364.                         format = 'html';
  365.                         mimeType = 'application/xhtml+xml';
  366.                         content = Zotero.Report.generateHTMLDetails(items, combineChildItems);
  367.                 }
  368.             }
  369.             catch (e){
  370.                 Zotero.debug(e);
  371.                 throw (e);
  372.             }
  373.             
  374.             var uri_str = 'data:' + (mimeType ? mimeType + ',' : '') + encodeURIComponent(content);
  375.             var ext_uri = ioService.newURI(uri_str, null, null);
  376.             var extChannel = ioService.newChannelFromURI(ext_uri);
  377.             
  378.             return extChannel;
  379.         }
  380.     };
  381.  
  382.     var TimelineExtension = new function(){
  383.         this.newChannel = newChannel;
  384.  
  385.         /*
  386.         queryString key abbreviations:  intervals = i  |  dateType = t  |  timelineDate = d
  387.         
  388.         interval abbreviations:  day = d  |  month = m  |  year = y  |  decade = e  |  century = c  |  millennium = i
  389.         dateType abbreviations:  date = d  |  dateAdded = da  |  dateModified = dm
  390.         timelineDate format:  shortMonthName.day.year  (year is positive for A.D. and negative for B.C.)
  391.         
  392.         
  393.         
  394.         zotero://timeline   -----> creates HTML for timeline 
  395.             (defaults:  type = library | intervals = month, year, decade | timelineDate = today's date | dateType = date)
  396.             
  397.             
  398.         Example URLs:
  399.         
  400.         zotero://timeline/library?i=yec
  401.         zotero://timeline/collection/12345?t=da&d=Jul.24.2008
  402.         zotero://timeline/search/54321?d=Dec.1.-500&i=dmy&t=d
  403.         
  404.         
  405.         
  406.         zotero://timeline/data    ----->creates XML file
  407.             (defaults:  type = library  |  dateType = date)
  408.         
  409.         
  410.         Example URLs:
  411.         
  412.         zotero://timeline/data/library?t=da
  413.         zotero://timeline/data/collection/12345
  414.         zotero://timeline/data/search/54321?t=dm
  415.         
  416.         */
  417.         function newChannel(uri) {
  418.             var ioService = Components.classes["@mozilla.org/network/io-service;1"]
  419.                 .getService(Components.interfaces.nsIIOService);
  420.  
  421.             var Zotero = Components.classes["@zotero.org/Zotero;1"]
  422.                 .getService(Components.interfaces.nsISupports)
  423.                 .wrappedJSObject;
  424.  
  425.             generateContent:try {
  426.                 var mimeType, content = '';
  427.     
  428.                 var [path, queryString] = uri.path.substr(1).split('?');
  429.                 var [intervals, timelineDate, dateType] = ['','',''];
  430.                 
  431.                 if (queryString) {
  432.                     var queryVars = queryString.split('&');
  433.                     for (var i in queryVars) {
  434.                         var [key, val] = queryVars[i].split('=');
  435.                         if(val) {
  436.                             switch (key) {
  437.                                 case 'i':
  438.                                     intervals = val;
  439.                                     break;
  440.                                 case 'd':
  441.                                     timelineDate = val;
  442.                                     break;
  443.                                 case 't':
  444.                                     dateType = val;
  445.                                     break;
  446.                             }
  447.                         }
  448.                     }
  449.                 }
  450.                 
  451.                 var pathParts = path.split('/');
  452.                 
  453.                 if (pathParts[0] != 'data') {
  454.                     //creates HTML file
  455.                     content = Zotero.File.getContentsFromURL('chrome://zotero/skin/timeline/timeline.html');
  456.                     mimeType = 'text/html';
  457.                     
  458.                     var [type, id] = pathParts;
  459.                                         
  460.                     if(!timelineDate){
  461.                         timelineDate=Date();
  462.                         var dateParts=timelineDate.toString().split(' ');
  463.                         timelineDate=dateParts[1]+'.'+dateParts[2]+'.'+dateParts[3];
  464.                     }
  465.                     if (intervals.length < 3) {
  466.                         intervals += "mye".substr(intervals.length);
  467.                     }
  468.                     
  469.                     var theIntervals = new Object();
  470.                         theIntervals['d'] = 'Timeline.DateTime.DAY';
  471.                         theIntervals['m'] = 'Timeline.DateTime.MONTH';
  472.                         theIntervals['y'] = 'Timeline.DateTime.YEAR';
  473.                         theIntervals['e'] = 'Timeline.DateTime.DECADE';
  474.                         theIntervals['c'] = 'Timeline.DateTime.CENTURY';
  475.                         theIntervals['i'] = 'Timeline.DateTime.MILLENNIUM';
  476.                     
  477.                     //sets the intervals of the timeline bands
  478.                     var theTemp = '<body onload="onLoad(';
  479.                     var a = (theIntervals[intervals[0]]) ? theIntervals[intervals[0]] : 'Timeline.DateTime.MONTH';
  480.                     var b = (theIntervals[intervals[1]]) ? theIntervals[intervals[1]] : 'Timeline.DateTime.YEAR';
  481.                     var c = (theIntervals[intervals[2]]) ? theIntervals[intervals[2]] : 'Timeline.DateTime.DECADE';
  482.                     content = content.replace(theTemp, theTemp + a + ',' + b + ',' + c + ',\'' + timelineDate + '\'');
  483.                     
  484.                     theTemp = 'document.write("<title>';
  485.                     if(type == 'collection') {
  486.                         var theCollection = Zotero.Collections.get(id);
  487.                         content = content.replace(theTemp, theTemp + theCollection.getName() + ' - ');
  488.                     }
  489.                     else if(type == 'search') {
  490.                         var theSearch = Zotero.Searches.get(id);
  491.                         content = content.replace(theTemp, theTemp + theSearch['name'] + ' - ');
  492.                     }
  493.                     else {
  494.                         content = content.replace(theTemp, theTemp + Zotero.getString('pane.collections.library') + ' - ');
  495.                     }
  496.                     
  497.                     theTemp = 'Timeline.loadXML("zotero://timeline/data/';
  498.                     var d = '';
  499.                     //passes information (type,ids, dateType) for when the XML is created
  500.                     if(!type || (type != 'collection' && type != 'search')) {
  501.                         d += 'library?t=' + dateType;
  502.                     }
  503.                     else {
  504.                         d += type + '/' + id + '?t=' + dateType;
  505.                     }
  506.                     content = content.replace(theTemp, theTemp + d);
  507.                     
  508.                     
  509.                     var uri_str = 'data:' + (mimeType ? mimeType + ',' : '') + encodeURIComponent(content);
  510.                     var ext_uri = ioService.newURI(uri_str, null, null);
  511.                     var extChannel = ioService.newChannelFromURI(ext_uri);
  512.  
  513.                     return extChannel;
  514.                 }
  515.                 else {
  516.                     //creates XML file
  517.                     var [, type, ids] = pathParts;
  518.                     
  519.                     switch (type){
  520.                         case 'collection':
  521.                             var col = Zotero.Collections.get(ids);
  522.                             var results = col.getChildItems();
  523.                             break;
  524.  
  525.                         case 'search':
  526.                             var s = new Zotero.Search(ids);
  527.                             var ids = s.search();
  528.                             break;
  529.  
  530.                         default:
  531.                             type = 'library';
  532.                             var s = new Zotero.Search();
  533.                             s.addCondition('noChildren', 'true');
  534.                             var ids = s.search();
  535.                     }
  536.  
  537.                     if (!results) {
  538.                         var results = Zotero.Items.get(ids);
  539.                     }
  540.                     var items = [];
  541.                     // Only include parent items
  542.                     for (var i = 0; i < results.length; i++) {
  543.                         if (!results[i].getSource()) {
  544.                             items.push(results[i]);
  545.                         }
  546.                     }
  547.  
  548.                     if (!items) {
  549.                         mimeType = 'text/html';
  550.                         content = 'Invalid ID';
  551.                         break generateContent;
  552.                     }
  553.  
  554.                     // Convert item objects to export arrays
  555.                     for (var i = 0; i < items.length; i++) {
  556.                         items[i] = items[i].toArray();
  557.                     }
  558.  
  559.                     mimeType = 'application/xml';
  560.  
  561.                 
  562.                     var theDateTypes = new Object();
  563.                         theDateTypes['d'] = 'date';
  564.                         theDateTypes['da'] = 'dateAdded';
  565.                         theDateTypes['dm'] = 'dateModified';
  566.                     
  567.                     //default dateType = date
  568.                     if (!dateType || !theDateTypes[dateType]) {
  569.                         dateType = 'd';
  570.                     }
  571.                 
  572.                     content = Zotero.Timeline.generateXMLDetails(items, theDateTypes[dateType]);
  573.  
  574.                 }
  575.                 
  576.                 var uri_str = 'data:' + (mimeType ? mimeType + ',' : '') + encodeURIComponent(content);
  577.                 var ext_uri = ioService.newURI(uri_str, null, null);
  578.                 var extChannel = ioService.newChannelFromURI(ext_uri);
  579.  
  580.                 return extChannel;
  581.             }
  582.             catch (e){
  583.                 Zotero.debug(e);
  584.                 throw (e);
  585.             }
  586.         }
  587.     };
  588.     
  589.     
  590.     /*
  591.         zotero://select/type/id
  592.     */
  593.     
  594.     var SelectExtension = new function(){
  595.         this.newChannel = newChannel;
  596.  
  597.         function newChannel(uri) {
  598.             var ioService = Components.classes["@mozilla.org/network/io-service;1"]
  599.                 .getService(Components.interfaces.nsIIOService);
  600.  
  601.             var Zotero = Components.classes["@zotero.org/Zotero;1"]
  602.                 .getService(Components.interfaces.nsISupports)
  603.                 .wrappedJSObject;
  604.  
  605.             generateContent:try {
  606.                 var mimeType, content = '';
  607.     
  608.                 var [path, queryString] = uri.path.substr(1).split('?');
  609.                 var [type, id] = path.split('/');
  610.                 
  611.                 //currently only able to select one item
  612.                 var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  613.                     .getService(Components.interfaces.nsIWindowMediator);
  614.                 var win = wm.getMostRecentWindow(null);
  615.                 
  616.                 if(!win.ZoteroPane.isShowing()){
  617.                     win.ZoteroPane.toggleDisplay();
  618.                 }
  619.                 
  620.                 win.ZoteroPane.selectItem(id);
  621.             }
  622.             catch (e){
  623.                 Zotero.debug(e);
  624.                 throw (e);
  625.             }
  626.         }
  627.     };
  628.  
  629.     
  630.     var ReportExtensionSpec = ZOTERO_SCHEME + "://report"
  631.     ReportExtensionSpec = ReportExtensionSpec.toLowerCase();
  632.     
  633.     this._extensions[ReportExtensionSpec] = ReportExtension;
  634.  
  635.     var TimelineExtensionSpec = ZOTERO_SCHEME + "://timeline"
  636.     TimelineExtensionSpec = TimelineExtensionSpec.toLowerCase();
  637.  
  638.     this._extensions[TimelineExtensionSpec] = TimelineExtension;
  639.     
  640.     var SelectExtensionSpec = ZOTERO_SCHEME + "://select"
  641.     SelectExtensionSpec = SelectExtensionSpec.toLowerCase();
  642.  
  643.     this._extensions[SelectExtensionSpec] = SelectExtension;
  644. }
  645.  
  646.  
  647. /*
  648.  * Implements nsIProtocolHandler
  649.  */
  650. ChromeExtensionHandler.prototype = {
  651.     scheme: ZOTERO_SCHEME,
  652.     
  653.     defaultPort : -1,
  654.     
  655.     protocolFlags : Components.interfaces.nsIProtocolHandler.URI_STD,
  656.     
  657.     allowPort : function(port, scheme) {
  658.         return false;
  659.     },
  660.     
  661.     newURI : function(spec, charset, baseURI) {
  662.         var newURL = Components.classes["@mozilla.org/network/standard-url;1"]
  663.             .createInstance(Components.interfaces.nsIStandardURL);
  664.         newURL.init(1, -1, spec, charset, baseURI);
  665.         
  666.         return newURL.QueryInterface(Components.interfaces.nsIURI);
  667.     },
  668.     
  669.     newChannel : function(uri) {
  670.         var ioService = Components.classes["@mozilla.org/network/io-service;1"]
  671.             .getService(Components.interfaces.nsIIOService);
  672.         
  673.         var chromeService = Components.classes["@mozilla.org/network/protocol;1?name=chrome"]
  674.             .getService(Components.interfaces.nsIProtocolHandler);
  675.         
  676.         var newChannel = null;
  677.         
  678.         try {
  679.             var uriString = uri.spec.toLowerCase();
  680.             
  681.             for (extSpec in this._extensions) {
  682.                 var ext = this._extensions[extSpec];
  683.                 
  684.                 if (uriString.indexOf(extSpec) == 0) {
  685.                     if (this._systemPrincipal == null) {
  686.                         var chromeURI = chromeService.newURI(DUMMY_CHROME_URL, null, null);
  687.                         var chromeChannel = chromeService.newChannel(chromeURI);
  688.                         
  689.                         // Cache System Principal from chrome request
  690.                         // so proxied pages load with chrome privileges
  691.                         this._systemPrincipal = chromeChannel.owner;
  692.                         
  693.                         var chromeRequest = chromeChannel.QueryInterface(Components.interfaces.nsIRequest);
  694.                         chromeRequest.cancel(0x804b0002); // BINDING_ABORTED
  695.                     }
  696.                     
  697.                     var extChannel = ext.newChannel(uri);
  698.                     // Extension returned null, so cancel request
  699.                     if (!extChannel) {
  700.                         var chromeURI = chromeService.newURI(DUMMY_CHROME_URL, null, null);
  701.                         var extChannel = chromeService.newChannel(chromeURI);
  702.                         var chromeRequest = extChannel.QueryInterface(Components.interfaces.nsIRequest);
  703.                         chromeRequest.cancel(0x804b0002); // BINDING_ABORTED
  704.                     }
  705.                     
  706.                     if (this._systemPrincipal != null) {
  707.                         // applying cached system principal to extension channel
  708.                         extChannel.owner = this._systemPrincipal;
  709.                     }
  710.                     
  711.                     extChannel.originalURI = uri;
  712.                     
  713.                     return extChannel;
  714.                 }
  715.             }
  716.             
  717.             // pass request through to ChromeProtocolHandler::newChannel
  718.             if (uriString.indexOf("chrome") != 0) {
  719.                 uriString = uri.spec;
  720.                 uriString = "chrome" + uriString.substring(uriString.indexOf(":"));
  721.                 uri = chromeService.newURI(uriString, null, null);
  722.             }
  723.             
  724.             newChannel = chromeService.newChannel(uri);
  725.         }
  726.         catch (e) {
  727.             throw Components.results.NS_ERROR_FAILURE;
  728.         }
  729.         
  730.         return newChannel;
  731.     },
  732.     
  733.     QueryInterface : function(iid) {
  734.         if (!iid.equals(Components.interfaces.nsIProtocolHandler) &&
  735.                 !iid.equals(Components.interfaces.nsISupports)) {
  736.             throw Components.results.NS_ERROR_NO_INTERFACE;
  737.         }
  738.         return this;
  739.     }
  740. };
  741.  
  742.  
  743. //
  744. // XPCOM goop
  745. //
  746.  
  747. var ChromeExtensionModule = {
  748.     cid: ZOTERO_PROTOCOL_CID,
  749.     
  750.     contractId: ZOTERO_PROTOCOL_CONTRACTID,
  751.     
  752.     registerSelf : function(compMgr, fileSpec, location, type) {
  753.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  754.         compMgr.registerFactoryLocation(
  755.             ZOTERO_PROTOCOL_CID, 
  756.             ZOTERO_PROTOCOL_NAME, 
  757.             ZOTERO_PROTOCOL_CONTRACTID, 
  758.             fileSpec, 
  759.             location,
  760.             type
  761.         );
  762.     },
  763.     
  764.     getClassObject : function(compMgr, cid, iid) {
  765.         if (!cid.equals(ZOTERO_PROTOCOL_CID)) {
  766.             throw Components.results.NS_ERROR_NO_INTERFACE;
  767.         }
  768.         if (!iid.equals(Components.interfaces.nsIFactory)) {
  769.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  770.         }
  771.         return this.myFactory;
  772.     },
  773.     
  774.     canUnload : function(compMgr) {
  775.         return true;
  776.     },
  777.     
  778.     myFactory : {
  779.         createInstance : function(outer, iid) {
  780.             if (outer != null) {
  781.                 throw Components.results.NS_ERROR_NO_AGGREGATION;
  782.             }
  783.             
  784.             return new ChromeExtensionHandler().QueryInterface(iid);
  785.         }
  786.     }
  787. };
  788.  
  789. function NSGetModule(compMgr, fileSpec) {
  790.     return ChromeExtensionModule;
  791. }
  792.